import { defineStore } from "pinia";

export const useUserStore = defineStore("user", {
    // 定义状态，初始化时从 localStorage 读取数据
    state: () => ({
        token: '',  // 确保有这个属性
        userInfo: {
            id: null,
            username: '',
            email: '',
            avatar: '',
            phone: '',
            majorId: '',
            role: '',
            majorName: ''
        }
    }),
    actions: {
        // 设置 token 并同时存入 localStorage
        setToken(token) {
            this.token = token;
        },
        // 设置用户信息并同时存入 localStorage
        setUseInfo(userInfo) {
            this.userInfo = userInfo;
        },
        // 退出登录时清除所有用户数据
        clearUserInfo() {
            // 清除 Pinia 中的数据
            this.token = '';
            this.userInfo = {
                id: null,
                username: '',
                email: '',
                avatar: '',
                phone: '',
                majorId: '',
                role: '',
                majorName: ''
            };
        },
    },
    // 使用 localStorage 进行持久化存储
    persist: {
        enabled: true,
        strategies: [
            {
                key: 'user',
                storage: localStorage,
                paths: ['token', 'userInfo']
            }
        ]
    }
});